package com.my.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.EsClient;
import com.my.entity.Person;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.junit.Test;

import java.io.IOException;
import java.util.Date;


public class Simple {

    //json转换⼯具对象
    private ObjectMapper mapper = new ObjectMapper();
    //es连接
    private RestHighLevelClient client = EsClient.getClient();
    //索引名字
    private String index = "person";

    /**
     * 添加⽂档, 存⼊数据
     * @throws IOException
     */
    @Test
    public void testCreateDoc() throws Exception {
        //1. 准备⼀个person数据
        Person person = new Person("6", "⽞武", 30, new Date());
        //2. 将person实体转换成json格式
        String json = mapper.writeValueAsString(person);
        //3. 准备⼀个request对象, 指定索引名字（⼿动指定id）
        IndexRequest request = new IndexRequest(index);
        //4. ⼿动指定id, 将json数据存⼊请求对象中,XContentType.JSON为存⼊数据类型
        request.id(person.getId()).source(json, XContentType.JSON);
        //5. 通过client对象执⾏添加
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
        //6. 输出返回结果
        System.out.println(resp.getResult().toString());
    }

    /**
     * 修改⽂档数据
     */
    @Test
    public void testUpdateDoc() throws Exception {
        //1. 准备⼀个person数据
        Person person = new Person("6", "⻘⻰", 23, new Date());
        //2. 将person实体转换成json格式
        String json = mapper.writeValueAsString(person);
        //2. 创建修改请求对象, 第⼀个参数: 索引名字, 第⼆个参数:修改的⽂档id
        UpdateRequest request = new UpdateRequest(index, person.getId());
        //设置修改后的内容, 第⼆个参数: ⽂档数据类型
        request.doc(json, XContentType.JSON);
        //3. 通过client对象执⾏
        UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
        //4. 输出返回结果
        System.out.println(update.getResult().toString());
    }


    /**
     * 根据id删除⽂档
     * @throws IOException
     */
    @Test
    public void testDeleteDoc() throws Exception {
        //1. 封装⽤于删除的请求对象, 第⼀参数:索引名字, 第⼆参数:⽂档id
        DeleteRequest request = new DeleteRequest(index, "6");
        //2. client执⾏
        DeleteResponse resp = client.delete(request, RequestOptions.DEFAULT);
        //3. 输出结果
        System.out.println(resp.getResult().toString());
    }

}
